package com.csg.boot.starter.builder;

import com.csg.boot.starter.constant.SecurityEnum;
import com.csg.boot.starter.constant.SwaggerProperties;
import springfox.documentation.service.*;

import java.util.List;

/**
 * @author george
 */
public class SecuritySchemeBuilder implements BaseBuilder<SecurityScheme, SwaggerProperties.SecurityProperties> {

    private static SecuritySchemeBuilder builder = new SecuritySchemeBuilder();

    private static AuthorizationScopeBuilder authorizationScopeBuilder = AuthorizationScopeBuilder.getInstance();

    private static GrantTypeBuilder grantTypeBuilder = GrantTypeBuilder.getInstance();

    private SecuritySchemeBuilder() {
    }

    public static SecuritySchemeBuilder getInstance() {
        return builder;
    }

    @Override
    public SecurityScheme build(SwaggerProperties.SecurityProperties properties) {
        SecurityEnum type = properties.getType();
        if (SecurityEnum.API_KEY.equals(type)) {
            return new ApiKey(properties.getName(), properties.getKeyName(), properties.getPassAs());
        } else if (SecurityEnum.BASIC_AUTH.equals(type)) {
            return new BasicAuth(properties.getName());
        } else if (SecurityEnum.OAUTH_2.equals(type)) {
            return new OAuth(properties.getName(), authorizationScopes(properties.getScopes()), grantTypes(properties.getGrantTypes()));
        }
        return null;
    }

    private List<AuthorizationScope> authorizationScopes(List<SwaggerProperties.AuthorizationScopeProperties> scopes) {
        return authorizationScopeBuilder.build(scopes);
    }

    private List<GrantType> grantTypes(List<SwaggerProperties.GrantProperties> grantProperties) {
        return grantTypeBuilder.build(grantProperties);
    }

}
